"""
测试均值回归策略

使用虚拟债券标的X：
- 价格服从均值为100，标准差为0.5的正态分布
- 票息为3%，一年付息2次，每次付息1.5%
"""
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from loguru import logger
import os
import sys
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)

from engine.engine import BacktestEngine
from engine.assets import Bond, AssetType
from engine.event import CashFlowType
from strategy.examples.bond_mean_reversion import BondMeanReversionStrategy
from visualization.performance import PerformanceAnalyzer, PerformanceVisualizer

def generate_test_data(start_date: datetime, end_date: datetime) -> pd.DataFrame:
    """
    生成测试数据
    
    Args:
        start_date: 起始日期
        end_date: 结束日期
        
    Returns:
        包含债券X价格数据的DataFrame
    """
    # 生成日期序列
    dates = pd.date_range(start=start_date, end=end_date, freq='D')
    
    # 生成服从正态分布的价格序列
    np.random.seed(42)  # 设置随机种子，确保结果可重现
    prices = np.random.normal(loc=100, scale=0.5, size=len(dates))
    
    # 创建DataFrame
    df = pd.DataFrame({
        'bond_X_close': prices,
        'bond_X_ytm': np.full(len(dates), 0.03),  # 假设YTM固定为3%
        'bond_X_volume': np.full(len(dates), 10000)  # 假设成交量固定为10000
    }, index=dates)
    
    return df

def main():
    """主函数"""
    # 设置回测参数
    start_date = datetime(2024, 1, 1)
    end_date = datetime(2025, 1, 1)
    initial_cash = 1000000.0  # 初始资金100万
    
    # 生成测试数据
    market_data = generate_test_data(start_date, end_date)
    
    # 计算付息日期
    days_between_payments = 365 // 2  # 半年付息一次
    first_payment_date = start_date + timedelta(days=days_between_payments)
    second_payment_date = first_payment_date + timedelta(days=days_between_payments)
    
    # 创建明确的现金流列表
    bond_cashflows = [
        (first_payment_date, 3.65/2, CashFlowType.INTEREST),   # 第一次付息 3%/2 = 1.5%
        (second_payment_date, 3.65/2, CashFlowType.INTEREST),  # 第二次付息 3%/2 = 1.5%
        (end_date, 100.0, CashFlowType.PRINCIPAL)  # 到期还本
    ]
    
    # 创建债券资产
    bond = Bond(
        symbol='bond_X',
        asset_type=AssetType.BOND,
        par_value=100.0,
        value_date=start_date,
        explicit_cashflows=bond_cashflows
    )
    
    # 创建策略
    strategy = BondMeanReversionStrategy(
        name="均值回归策略测试",
        lookback_period=100,  # 使用20天的回看期
        std_multiplier=1.5,  # 使用2倍标准差
        leverage=1.0  # 不使用杠杆
    )
    
    # 创建回测引擎
    engine = BacktestEngine(
        initial_capital=initial_cash,
        commission_rate=0.0000,  # 手续费率0.03%
        slippage_rate=0.0000  # 滑点率0.02%
    )
    
    # 添加资产和数据
    engine.add_asset(bond)
    
    # 将市场数据分别添加到对应的资产
    bond_data = market_data[['bond_X_close', 'bond_X_ytm', 'bond_X_volume']].copy()
    bond_data.columns = ['close', 'ytm', 'volume']
    engine.add_market_data('bond_X', bond_data)
    
    # 设置策略
    engine.set_strategy(strategy)
    
    # 运行回测
    print("开始运行回测...")
    results = engine.run_backtest()
    results.to_csv('results.csv',)
    print(results)
    
    # 创建性能分析器和可视化器
    analyzer = PerformanceAnalyzer(results=results)
    visualizer = PerformanceVisualizer(analyzer=analyzer,trades=engine.trades)
    
    # 确保reports目录存在
    os.makedirs('reports', exist_ok=True)
    
    # 生成HTML报告
    report_path = "reports/example4_report.html"
    visualizer.export_html_report(filename=report_path)
    print(f"\nHTML报告已保存至: {report_path}")
    
    # 自动打开报告
    report_absolute_path = os.path.abspath(report_path)
    import webbrowser
    webbrowser.open('file://' + report_absolute_path)

if __name__ == "__main__":
    main()
